import React from 'react'
import { Button } from 'antd'
import { SchemaForm, Item, Submit, Layout, SchemaType } from '@amazebird/antd-schema-form'

const data = {
  admin: ['王大锤', '王大仙', '王二狗']
}

const schema: SchemaType = {
  admin: {
    type: 'array',
    label: '管理员',
    required: true,
    item: {
      name: '姓名',
      component: 'Input'
    }
  }
}

function MoveUp(move, index) {
  if (index > 0) {
    move(index, index - 1)
  }
}

function MoveDown(move, index, fields) {
  if (index < fields.length - 1) {
    move(index, index + 1)
  }
}

function SimpleForm() {
  const onFinish = (formdata) => {
    console.info(formdata)
  }

  return (
    <SchemaForm schema={schema} initialValues={data}>
      <Item field="admin">
        {(fields, { add, remove, move }) => {
          return (
            <>
              {
                fields.map((field, index) => {
                  return (
                    <div style={{ display: 'flex', marginBottom: 8, alignItems: 'baseline' }} key={field.key}>
                      <Item {...field} />
                      <Button onClick={() => remove(field.name)}>删除</Button>
                      <Button onClick={() => MoveUp(move, index)}>上移</Button>
                      <Button onClick={() => MoveDown(move, index, fields)}>下移</Button>
                    </div>
                  )
                })
              }
              <Button onClick={() => add()}>添加用户</Button>
            </>
          )
        }}
      </Item>
      <Layout offset={8}>
        <Submit type="primary" onFinish={onFinish} >保存</Submit>
      </Layout>
    </SchemaForm>
  )
}

export default SimpleForm
